<template>
  <view class="page">
    <view class="date-range-selector">
      <view
        class="item"
        v-for="item in details.statistical"
        :key="item"
        @click="
          () => {
            currentSelectDateRange = item
            resetPaginationReloadData()
          }
        "
        :class="{ active: item === currentSelectDateRange }"
        >{{ item }}</view
      >
    </view>
    <view class="info">
      <view class="content">
        <view class="title">
          <!--					活动名称-->
          <view class="randListName">{{ details.rankingListName }}</view>
          <view class="duration">
            <!--					活动时长-->
            <text v-if="details.startEndTimeInterval.y > 0">{{ `${details.startEndTimeInterval.y} year` }}</text>
            <text v-else-if="details.startEndTimeInterval.m > 0">{{ `${details.startEndTimeInterval.m} month` }}</text>
            <text v-else-if="details.startEndTimeInterval.w > 0">{{ `${details.startEndTimeInterval.w} week` }}</text>
            <text v-else>{{ `${details.startEndTimeInterval.d} day` }}</text>
          </view>
        </view>

        <view class="sub-title">
          <text>排行榜 RANKING LIST</text>
        </view>

        <view class="rules">
          <view
            ><text>活动规则：{{ details.activityRule }}</text></view
          >
          <!--          <view>-->
          <!--            <text>{{ details.activityRule }}</text>-->
          <!--          </view>-->
          <!--					活动时间-->
          <view>{{ `活动时间：${details.startTimeFormat}至${details.endTimeFormat}` }}</view>
        </view>
      </view>
      <!--			排行榜状态-->
      <!--			进行中-->
      <image class="rank-status" :src="rankInProcessIcon" v-if="details.isLock === 0"></image>
      <!--			已封榜-->
      <image class="rank-status" v-else-if="details.isLock === 1" :src="rankInLockIcon"></image>
    </view>

    <view class="rank-list">
      <!--			表头-->
      <view class="table-header column">
        <view class="item column-item-1 column-item">排名</view>
        <view class="item column-item-2 column-item">用户</view>
        <view class="item column-item-3 column-item" style="color: #a75b07">打卡天数</view>
        <view class="item column-item-4 column-item" style="color: #a75b07">累计学习时长</view>
      </view>
      <!--			表体-->
      <template v-if="recordList.length > 0 || userRankInfo">
        <!--				用户自己的排名信息-->
        <template v-if="userRankInfo">
          <rank-item v-if="userRankInfo" :item="userRankInfo" :rank="userRankInfo.userRank" :primary="true"></rank-item>
        </template>

        <!--				所有用户排名信息-->
        <rankItem v-for="(item, index) in recordList" :key="item.userId" :rank="index + 1" :item="item"></rankItem>
        <uni-load-more :status="loadMoreStatusText"></uni-load-more>
      </template>
      <empty v-else height="760rpx"></empty>
    </view>

    <!--		跳转到活动自习室-->
    <view class="view-more-footer" @click="() => $refs.enterToStudyRoom.enterToStudyRoom(details.studyRoomId)" v-if="details.studyRoomId">
      <image class="icon" :src="getShowNginxPicUrl('GJaC5bfv9AiT6neLTVfp.png')" mode="widthFix"></image>
      <view class="text">前往打卡自习室</view>
      <view class="btn">去自习</view>
    </view>

    <!--		跳转回自习室-->
    <enterToStudyRoom ref="enterToStudyRoom" from-page="/studyRoom/pages/activity/list"></enterToStudyRoom>
    <!--		跳转到活动详情浮窗-->
    <activityDetailFloat :studyActivityId="details.studyActivityId"></activityDetailFloat>
  </view>
</template>

<script>
import { getShowImage } from "@/utils"
import request from "@/utils/request"
import uniLoadMore from "@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue"
import dateUtils from "@/utils/dateUtils"
import moment from "@/lib/moment.min"
import empty from "@/components/empty.vue"
import rankInLockIcon from "./assets/rank_in_lock.png"
import rankInProcessIcon from "./assets/rank_in_process.png"
import { getShowNginxPicUrl } from "@/utils/settings"
import enterToStudyRoom from "@/studyRoom/components/enterToStudyRoom/index.vue"
import activityDetailFloat from "@/studyRoom/components/activityDetailFloat/index.vue"
import rankItem from "./components/rankItem.vue"

export default {
  components: {
    uniLoadMore,
    empty,
    enterToStudyRoom,
    activityDetailFloat,
    rankItem,
  },
  data() {
    return {
      details: {
        rankingListId: "",
        rankingListName: "",
        rankingListSort: 0,
        rankingStatistical: "",
        statistical: [],
        isPresent: 0,
        studyActivityId: "",
        activityTypeId: null,
        studyRoomId: 0,
        activityRule: "",
        activityBackground: "",
        isLock: 0,
        startTime: "",
        endTime: "",
        studyRoomUserList: {},
        startEndTimeInterval: {
          d: 0,
          m: 0,
          w: 0,
          y: 0,
        },
        startTimeFormat: "",
        endTimeFormat: "",
      },
      recordList: [],
      currentSelectDateRange: "", //当前选择的日期区间
      pagination: {
        current: 1,
        size: 15,
      },
      loadMoreStatusText: "more",
      rankInLockIcon,
      rankInProcessIcon,
      queryParams: {
        studyActivityId: "",
      },
      userRankInfo: null, //用户的排名信息
    }
  },
  onLoad(query) {
    this.queryParams.studyActivityId = query.studyActivityId
    //获取活动详情
    this.getActivityDetails().then(() => {
      //默认选中第一个区间
      this.currentSelectDateRange = this.details.statistical[0]
      //刷新列表
      this.resetPaginationReloadData()
    })
  },
  methods: {
    getShowNginxPicUrl,
    getShowImage,
    //获取活动详情
    async getActivityDetails() {
      this.details = await request({
        url: "studyRankingList/getStatistical",
        data: {
          studyActivityId: this.queryParams.studyActivityId,
        },
        errorHandle: true,
        showLoading: true,
      })
      //动态设置页面标题
      uni.setNavigationBarTitle({
        title: this.details.rankingListName,
      })
      //计算开始时间和结束时间之间的时间间隔
      this.details.startEndTimeInterval = dateUtils.moment.calculateDateInterval(
        moment(this.details.startTime),
        moment(this.details.endTime),
      )
      //格式化活动时间
      const startTime = moment(this.details.startTime)
      this.details.startTimeFormat = `${startTime.get("year")}年${startTime.get("month") + 1}月${startTime.get("date")}日`
      const endTime = moment(this.details.endTime)
      this.details.endTimeFormat = `${endTime.get("month") + 1}月${endTime.get("date")}日`
    },
    // 获取排行榜记录
    getRecordList() {
      return new Promise((resolve, reject) => {
        if (this.loadMoreStatusText === "loading") {
          resolve()
          return
        }
        this.loadMoreStatusText = "loading"
        request({
          url: "studyRankingList/userRankDetail",
          data: {
            page: this.pagination.current,
            size: this.pagination.size,
            currentRanking: this.currentSelectDateRange,
            studyActivityId: this.queryParams.studyActivityId,
          },
          errorHandle: true,
        }).then((data) => {
          //格式化累计学习时长
          for (let record of data.records) {
            record.duration = dateUtils.formatTimeObject2(record.totalStudyDuration)
          }
          this.recordList.push(...data.records)
          if (this.recordList.length >= data.total) {
            this.loadMoreStatusText = "noMore"
          } else {
            this.loadMoreStatusText = "more"
          }
          resolve()
        })
      })
    },
    // 重置分页并重新加载数据
    resetPaginationReloadData() {
      this.pagination.current = 1
      this.recordList = []
      uni.showLoading({
        title: "加载中",
      })
      this.getRecordList().finally(() => {
        uni.hideLoading()
      })
      //查询用户当前的排名
      request({
        url: "studyRankingList/getRankingByUserId",
        data: {
          currentRanking: this.currentSelectDateRange,
          studyActivityId: this.queryParams.studyActivityId,
        },
        showLoading: true,
      })
        .then((data) => {
          if (data) {
            //格式化累计学习时长
            data.duration = dateUtils.formatTimeObject2(data.totalStudyDuration)
            this.userRankInfo = data
          }
        })
        .catch((err) => {
          console.log(err, "err")
        })
    },
  },
  //滑到底部自动加载下一页
  onReachBottom() {
    if (this.loadMoreStatusText === "noMore") {
      return
    }
    this.pagination.current++
    this.getRecordList()
  },
}
</script>

<style lang="scss" scoped>
@import "./common";

.page {
  min-height: 100vh;
  background: #f0ede1;
  padding-bottom: calc(200rpx + env(safe-area-inset-bottom));
  .date-range-selector {
    display: flex;
    justify-content: space-around;
    padding: 20rpx 50rpx;
    .item {
      font-size: 32rpx;
      position: relative;
      &.active {
        color: #1681f7;
      }
      &.active::after {
        content: "";
        position: absolute;
        bottom: -16rpx;
        left: 0;
        width: 100%;
        height: 6rpx;
        background: #1681f7;
      }
    }
  }
  > .info {
    min-height: 398rpx;
    position: relative;
    background: url("https://kou.gdzmtech.com/pic/QYJ1C9kDbpeH3B9JXhNY.png") no-repeat right bottom;
    background-size: 366.8rpx 250.6rpx;
    .content {
      padding: {
        left: 50rpx;
        top: 40rpx;
      }
      .title {
        font-size: 46rpx;
        font-weight: bold;
        display: flex;
        .randListName {
          max-width: 430rpx;
          //文本溢出加省略号
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .duration {
          margin-left: 12rpx;
          color: #a75b07;
        }
      }
      .sub-title {
        font-size: 34rpx;
        font-weight: bold;
        margin-top: 10rpx;
      }
      .rules {
        margin-top: 20rpx;
        font-size: 30rpx;
        color: #5c3205;
        line-height: 1.6;
        max-width: 510rpx;
      }
    }
    .rank-status {
      position: absolute;
      left: 490rpx;
      top: 96rpx;
      width: 147.72rpx;
      height: 133.66rpx;
    }
  }

  > .rank-list {
    background: var(--background-color);
    border-radius: 40rpx;
    padding: 20rpx 10rpx;
    min-height: 920rpx;
    .table-header {
      .item {
        font-size: 30rpx;
        color: #666060;
      }
    }
  }

  > .view-more-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.1);
    padding: {
      bottom: env(safe-area-inset-bottom);
      left: 40rpx;
      right: 40rpx;
    }
    display: flex;
    align-items: center;
    justify-content: space-between;

    > .icon {
      width: 150rpx;
      max-height: 150rpx;
    }

    > .text {
      color: #666060;
      font-size: 32rpx;
    }

    > .btn {
      padding: 10rpx 40rpx;
      border-radius: 31rpx;
      background: #54bd81;
      color: white;
      font-size: 32rpx;
    }
  }
}
</style>
